<?php

namespace App\Services\Purchase;

use App\CodeResponse;
use App\Enum;
use App\Models\Purchase\PurchaseReturnOrder;
use App\Repositories\Basic\StorageRepository;
use App\Repositories\Basic\SupplierRepository;
use App\Repositories\Purchase\PurchaseReturnOrderRepository;
use App\Services\BaseService;
use App\Services\Stock\ProductStockService;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PurchaseReturnOrderService extends BaseService
{

    public function createOrder($params)
    {
        $this->checkParams($params);
        //获取操作用户ID
        $params['user_id'] = get_user_id();

        //生成订单号
        $params['order_no'] = $this->generateOrderNO();

        return app(PurchaseReturnOrderRepository::class)->create($params);
    }


    /**
     * 生成采购订单编号
     */
    public function generateOrderNo()
    {
        return retry(5, function () {
            $randomNumber = str_pad(random_int(1, 9999), 4, '0', STR_PAD_LEFT);
            $orderNo = 'CGTH' . date('YmdHis') . $randomNumber;
            if (!$this->isOrderNoUsed($orderNo)) {
                return $orderNo;
            }
            $this->throwBusinessException(CodeResponse::FAIL, '订单号获取失败');
        });
    }

    public function isOrderNoUsed($orderNo)
    {
        return app(PurchaseReturnOrderRepository::class)->isExists(['order_no' => $orderNo]);
    }


    public function updateOrder($id, $params)
    {
        $this->checkParams($params);
        $this->updateCheck($id);
        //获取操作用户ID
        $params['user_id'] = get_user_id();

        return app(PurchaseReturnOrderRepository::class)->update($id, $params);
    }

    /**
     * @param $PurchaseReturnOrder
     * @return bool
     */
    public function isPendingOrder($PurchaseReturnOrder)
    {
        return $PurchaseReturnOrder->status == Enum::PURCHASE_RETURN_ORDER_STATUS_PENDING ? true : false;
    }

    protected function checkParams($params)
    {
        //判断供应商是否有效
        $supplier = app(SupplierRepository::class)->getById($params['supplier_id']);

        if (!$supplier) {
            $this->throwBusinessException(CodeResponse::FAIL, '查询不到供应商，supplier_id错误');
        }

        //判断仓库是否有效
        $storage = app(StorageRepository::class)->getById($params['storage_id']);
        if (!$storage) {
            $this->throwBusinessException(CodeResponse::FAIL, '查询不到仓库，storage_id错误');
        }

    }


    public function cancelOrder($id)
    {
        $this->updateCheck($id);
        return app(PurchaseReturnOrderRepository::class)->update($id, ['status' => Enum::PURCHASE_RETURN_ORDER_STATUS_CANCEL]);

    }

    public function updateCheck($id)
    {
        $PurchaseReturnOrder = app(PurchaseReturnOrderRepository::class)->getById($id);
        if (!$PurchaseReturnOrder) {
            $this->throwBusinessException(CodeResponse::FAIL, '获取订单失败,id错误');
        }
        if (!$this->isPendingOrder($PurchaseReturnOrder)) {
            $this->throwBusinessException(CodeResponse::FAIL, '订单不是待审核状态，不能进行修改');
        }
    }


    public function saveTotalCostPrice($id)
    {
        //获取所有条目的total_price
        $PurchaseReturnOrder = PurchaseReturnOrder::lockForUpdate()->find($id);
        if (!$this->isPendingOrder($PurchaseReturnOrder)) {
            $this->throwBusinessException(CodeResponse::FAIL, '此订单已非待审状态，不支持操作');

        }
        $totalCostPrice = $PurchaseReturnOrder->PurchaseReturnItems()->sum('total_price');
        return PurchaseReturnOrder::where('id', $id)->update(['total_cost_price' => $totalCostPrice]);

    }

    /**
     * 申请审核
     * @param $id
     * @return bool
     * @throws \App\Exceptions\BusinessException
     */
    public function review($id): bool
    {
        //开启事务
        DB::beginTransaction();
        try {
            $purchaseReturnOrder = PurchaseReturnOrder::lockForUpdate()->find($id);
            if (!$this->isPendingOrder($purchaseReturnOrder)) {
                $this->throwBusinessException(CodeResponse::FAIL, '此订单已非待审状态，不支持操作');
            }
            //产品库存记录处理
            $purchaseItems=$purchaseReturnOrder->purchaseReturnItems()->get();
            ProductStockService::getInstance()->initData($purchaseItems,$purchaseReturnOrder['storage_id'])->handlePurchaseReturn();
            //修改采购退货订单状态
            PurchaseReturnOrder::where('id', $id)->update([
                'status' => Enum::PURCHASE_RETURN_ORDER_STATUS_APPROVED,
                'review_at' => date('Y-m-d H:i:s'),
                'finished_at' => date('Y-m-d H:i:s'),
                'review_user_id' => get_user_id()
            ]);

            DB::commit();
            return true;
        } catch (QueryException $exception) {
            DB::rollBack();
            Log::error($exception->getMessage());
            return false;

        }

    }



}